
/* <<< COPYRIGHT START >>>
 * Copyright 2006-Present OxygenSoftwareLibrary.com
 * Licensed under the GNU Lesser General Public License.
 * http://www.gnu.org/licenses/lgpl.html
 * 
 * @author: Ugorji Dick-Nwoke
 * <<< COPYRIGHT END >>>
 */


import java.lang.reflect.Method;

import org.python.core.Py;
import org.python.core.PyObject;
import org.python.core.PyString;

import oxygen.jython.OxyJythonInterpreter;

public class wljython extends OxyJythonInterpreter{
  private boolean mShowprompt;
  private PyObject defPS1;
  
  private static String lsep = System.getProperty("line.separator");
  private static String initstr = 
    "import wl" + lsep + 
    "import sys" + lsep + 
    "from jarray import array" + lsep + 
    "from java.lang import *" + lsep + 
    "interp.easysyntax(1)" + lsep + 
    //"wl.setvars('failonerror')" + lsep + 
    //"" + lsep + 
    //"" + lsep + 
    "";
  
  public wljython() throws Exception {
    super();
    defPS1 = Py.getSystemState().ps1;
    mShowprompt = true;
    exec(initstr);
  }
  
  public boolean showprompt(boolean b) {
    mShowprompt = b;
    return mShowprompt;
  }
  
  public boolean showprompt() {
    return mShowprompt;
  }
  
  public boolean push(String line) {
    boolean moreneeded = super.push(line);
    if(!moreneeded) {
      if(mShowprompt) {
        try {
          Py.getSystemState().ps1 = new PyString(getPrompt());
        } catch(Throwable thr) {
          throw new RuntimeException(thr);
        }
      } else {
        Py.getSystemState().ps1 = defPS1;
      }
    }
    return moreneeded;
  }
  
  public void help() {
    super.help();
    String s = "To toggle the prompt, use interp.showprompt(1) or interp.showprompt(0)";
    System.out.println(s);
  }
  
  private static String getPrompt() {
    //return wl.getprompt().toString();
    try {
      Method m = Class.forName("wl").getMethod("getprompt", null);
      return m.invoke(null, null).toString();
    } catch(RuntimeException rexc) {
      throw rexc;
    } catch (Exception exc) {
      throw new RuntimeException("exc");
    }
  }
  
  public static void main(String[] args) throws Exception {
    System.setProperty("python.console", "wljython");
    org.python.util.jython.main(args);
  }

}

